const apiURL = 'https://bizain.net'
const util = require('./util.js')


const wxRequest = (params = {}, url) => {
  const APP = getApp() || {}
  // 读取缓存接口数据
  if (params.fromCache && APP.globalData && APP.globalData[url]) {
    params.success(APP.globalData[url])
    return
  }
//封装网络请求
  wx.request({
    url,
    method: params.method || 'GET',
    data: params.data || {},
    header: {
      Accept: 'application/json',
      'x-biz-redpacketapp-token': APP.globalData.UserRes && APP.globalData.code ? APP.globalData.token : '',
    },
    success(res) {
      if (params.success) {
        if (res.statusCode === 200) { // 网络问题报错(wxRequest)
          if (res.data.errno && res.data.errno !== 0) { // 业务逻辑报错
            // res.data.errmsg && (params.fail || util.alert)(res.data.errmsg || '')
            if (APP.globalData && params.fromCache) {
              APP.globalData[url] = res.data
            }
            params.success(res)
          } else {
            if (APP.globalData && params.fromCache) {
              APP.globalData[url] = res.data
            }
            params.success(res)
          }
        } else {
          // App.onError(`Fail API: ${url}\r\nreturn: ${JSON.stringify(res)}`)
          (params.fail || util.alert)(res.data || '服务器响应异常，请稍后再试')
        }
      }
    },
    fail(res) {
      // console.log(res)
      util.alert('数据加载失败，请确认网络连接顺畅或稍后重试', () => {
        if (params.fail) {
          params.fail(res)
        }
      })
    },
    complete(res) {
      if (params.complete) {
        params.complete(res)
      }
    }
  })
}



// 所有接口
const balance = (params) => {
  params.data = { classid: 2 }
  wxRequest(params, `${apiURL}/redpacket/api/balance`)
}
const _login = (params) => {
  wxRequest(params, `${apiURL}/redpacket/api/login`)
}
const grabbed = (params) => {
  wxRequest(params, `${apiURL}/redpacket/api/grabbed/packet`)
}
const create = (params) => {
  wxRequest(params, `${apiURL}/redpacket/api/create`)
}
const details= (params) => {
  wxRequest(params, `${apiURL}/redpacket/api/details/packet`)
}

const openWallet = (params) => {
  wxRequest(params, `${apiURL}/redpacket/api/grab`)
}
const allDetails = (params) => {
  wxRequest(params, `${apiURL}/redpacket/api/details/packet`)
}
const recordReceive = (params) => {
  wxRequest(params, `${apiURL}/redpacket/api/receive/user`)
}
const recordSend = (params) => {
  wxRequest(params, `${apiURL}/redpacket/api/send/user`)
}

//输出接口方便调用
module.exports = {
  balance,//余额，在index.js和send.js中调用
  _login,//登录，在APP.js中调用
  grabbed,//判断用户是否抢过红包，在split中调用
  create,//创建红包，在send.js中调用
  details,//创建的红包信息，在send.js中调用
  allDetails,//红包被抢信息,在result.js中调用
  openWallet,//抢红包，在split.js中调用
  recordReceive,//收到的红包信息，在record中调用
  recordSend,//发送的红包信息，在record中调用
  request: function (url, opts) {
    wxRequest(opts, `${apiURL}${url}`)
  }//简化wx.request网络请求
}
